package com.alignet.gn.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Blob;
import java.sql.Timestamp;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ComponentSystemEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.MDC;
import org.hibernate.Hibernate;
import org.primefaces.event.IdleEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.alignet.gn.hibernate.TgnSolicitud;
import com.alignet.gn.hibernate.dao.TgnRequestDAO;
import com.alignet.gn.service.AccessService;
import com.alignet.gn.service.impl.Constants;
import com.alignet.gn.sesion.Eventos;
import com.alignet.gn.util.GNUtils;
import com.alignet.gn.util.Result;
import com.alignet.vpos.logging.MDCParams;

@Scope("request")
@Component("access")
public class AccessBean implements Serializable {

	private static final long serialVersionUID = 4089937794197364975L;
	private static final Logger log = LoggerFactory.getLogger(AccessBean.class);
	private static  org.apache.log4j.Logger logMdc = org.apache.log4j.Logger.getLogger("applog");

	@ManagedProperty(value = "#{accessService}")
	private AccessService service;

	@Autowired
	public void setTransactionBean(AccessService service) {
		this.service = service;
	}

	private String login = "";
	private String password = "" ;
	private String pageResponse;
	private String message;

	public void prueba(ComponentSystemEvent  event) {
		Result result = service.prueba();
	}
	public void process(ActionEvent event) {
		
		Result result = service.processAcces(login, password);	
		
		 
		InetAddress direccion;
		HttpServletRequest req= ( HttpServletRequest ) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		String ipClient=req.getRemoteAddr();
		try {
			direccion = InetAddress.getLocalHost();
			byte direccionIp[] = direccion.getAddress();
			MDC.put(MDCParams.SERVERIP,(Integer.valueOf(direccionIp[0]) +256)+"."+direccionIp[1]+"."+direccionIp[2]+"."+direccionIp[3]);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		MDC.put(MDCParams.USER, login);
		MDC.put(MDCParams.CLIENTIP, ipClient);
		MDC.put(MDCParams.APPNAME, "GN Modulo Comercio");
		MDC.put(MDCParams.EVENT, "Login");
		MDC.put(MDCParams.CLRPAN, MDCParams.CLRPAN_NOT_SHOWN);
		//String ipClient=request.getRemoteAddr();
		if(result.isSuccess()){
			//LOG.debug(bundle.getString(result.getCode()), result.getArgs());
			this.message = GNUtils.getMessage(result.getMessage());
			pageResponse = "success";
			MDC.put(MDCParams.STATUS, MDCParams.STATUS_SUCCESSFUL);
			logMdc.info("");
		} else {
			//LOG.debug(bundle.getString(result.getCode()), result.getArgs());
			MessagesController.addError(result.getCode());
			this.message = GNUtils.getMessage(result.getCode());
			pageResponse = "error";
			MDC.put(MDCParams.STATUS, MDCParams.STATUS_FAIL);
			logMdc.info("Usuario y/o clave incorrecto");
		}
		//HttpServletRequest request = ( HttpServletRequest )FacesContext.getCurrentInstance().getExternalContext().getRequest();
		//request.setAttribute("eventos", ev);
		limpiaMDC();
	}

	public void validateAccess(ComponentSystemEvent event){
		FacesContext fc = FacesContext.getCurrentInstance();
 		final UIComponent components = event.getComponent();
		final UIInput uiLogin = (UIInput)components.findComponent("login");
		final UIInput uiPass = (UIInput)components.findComponent("password");
		boolean ok = true;
		String ms = "";
		
		if(uiLogin.getLocalValue() == null  |  uiPass.getLocalValue() == null ){
			ms="Datos de acceso son requeridos.";
			ok= false;
		}else{
			final String login = uiLogin.getLocalValue().toString().trim();
			final String pass = uiPass.getLocalValue().toString().trim();
			
			if(!login.matches("^[a-zA-Z0-9]*$") || !pass.matches("^[a-zA-Z0-9]*$")){
				ms = GNUtils.getMessage("access.invalid");
	 			ok= false;
			}
		}
		if(!ok){
			FacesMessage msg = new FacesMessage("Acceso Denegado.", ms);
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			fc.addMessage(components.getClientId(fc), msg);
			fc.renderResponse();			
		}
	}
	
	
	
	public String processAction() {
		return pageResponse;
	}
	
	
    
	public String logout2() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        //return "home.xhtml?faces-redirect=true";
        return "/faces/index.jsp?faces-redirect=true";
    }

	// LISTENER
	public void idleListener(IdleEvent event) {    
		    //invalidate session
		    message = "Message from server: Your session is closed";
		    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	        request.getSession().invalidate();		    
	} 
    
	public String getLogin() {
	    return login;
	}

	public void setLogin(String login) {
	    this.login = login;
	}

	public String getPassword() {
	    return password;
	}

	public void setPassword(String password) {
	    this.password = password;
	}

	public String getMessage() {
		return message;
	}

	
	public static void limpiaMDC() {
		MDC.remove(MDCParams.USER);
		MDC.remove(MDCParams.SERVERIP);
		MDC.remove(MDCParams.APPNAME);
		MDC.remove(MDCParams.STATUS);
		MDC.remove(MDCParams.EVENT);
		MDC.remove(MDCParams.CLRPAN);
		MDC.remove(MDCParams.CLIENTIP);
	}




}
